今日我們將要介紹ES官方提供go-elasticsearch客戶端的基本操作。
用go get安裝 go-elasticsearch
go get github.com/elastic/go-elasticsearch/v8
建立elasticsearch客戶端的連線設定
package main
import (
	"log"
	"github.com/elastic/go-elasticsearch/v8"
	"github.com/elastic/go-elasticsearch/v8/esapi"
)
var es *elasticsearch.Client
func setElkClient() {
    var err error
	cfg := elasticsearch.Config{
		Addresses: []string{"http://127.0.0.1:9200"},
	}
	es, err = elasticsearch.NewClient(cfg)
	if err != nil {
		panic(err) // 連線失敗
	}
}
func main() {
	setElkClient()
	fmt.Println(es.Info())
}
{
  "name" : "CY-HUANG",
  "cluster_name" : "elasticsearch_huang",
  "cluster_uuid" : "05loK4i4TVmTdRBUHEpi5g",
  "version" : {
    "number" : "7.14.1",
    "build_flavor" : "default",
    "build_type" : "tar",
    "build_hash" : "66b55ebfa59c92c15db3f69a335d500018b3331e",
    "build_date" : "2021-08-26T09:01:05.390870785Z",
    "build_snapshot" : false,
    "lucene_version" : "8.9.0",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}
建立索引
func createIndex() {
	req := esapi.IndicesCreateRequest{
		Index: "test_index",
	}
	res, err := req.Do(context.Background(), es)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	log.Println(res)
}
[200 OK] {"acknowledged":true,"shards_acknowledged":true,"index":"test_index"}
新增資料,如果索引不存在,則會自動建立索引。
func IndexRequest() {
	req := esapi.IndexRequest{
		Index: "test_index",
		Body:  strings.NewReader(`{"title":"go es index test", "Content": "elasticsearch client"}`),
	}
	res, err := req.Do(context.Background(), es)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	log.Println(res)
}
[201 Created] {"_index":"test_index","_type":"_doc","_id":"6NwZS3wB63oJvfCKy9ZX","_version":1,"result":"created","_shards":{"total":2,"successful":1,"failed":0},"_seq_no":0,"_primary_term":1}
使用Query DSL語法查詢資料
func searchRequest() {
	req := esapi.SearchRequest{
		Index: []string{"test_index"},
		Body:  strings.NewReader(`{"from":0,"query":{"bool":{"must":[{"match":{"title":{"operator":"and","query":"go es index test"}}}]}},"size":20}`),
	}
	res, err := req.Do(context.Background(), es)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	log.Println(res)
}
[200 OK] {"took":0,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"max_score":1.1507283,"hits":[{"_index":"test_index","_type":"_doc","_id":"6NwZS3wB63oJvfCKy9ZX","_score":1.1507283,"_source":{"title":"go es index test", "Content": "elasticsearch client"}}]}}
删除索引
func deleteIndex() {
	req := esapi.IndicesDeleteRequest{
		Index: []string{"test_index"},
	}
	res, err := req.Do(context.Background(), es)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	log.Println(res)
}
[200 OK] {"acknowledged":true}
如需了解更多go-elasticsearch訊息請參閱